package com.nineclock.common.filter;

import cn.hutool.core.util.StrUtil;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.JsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;


@WebFilter("/*")
public class CurrentUserFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String name = authentication.getName();
           // System.err.println("===================================" + name);

            if (name != null && !"anonymousUser".equals(name)){
                UserInfo userInfo = JsonUtils.toBean(name, UserInfo.class);
                CurrentUserHolder.set(userInfo);
            }
            chain.doFilter(request,response);   //放行
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } finally {
            CurrentUserHolder.remove();  //移除
        }
    }
}
